package com.hongdee.crm.saMessage.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.carConfig.dao.ITCrmCarRefDao;
import com.hongdee.crm.saMessage.dao.ITCrmCarSaMessageDao;
import com.hongdee.crm.saMessage.entity.TCrmCarSaMessage;
import com.hongdee.crm.saMessage.service.ITCrmCarSaMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 名  称:TCrmCarSaMessageServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.crm.saMessage.service.impl
 * 作  者: 术洪超
 * 日  期:2017-03-21 17:02
 */
@Service
public class TCrmCarSaMessageServiceImpl implements ITCrmCarSaMessageService {

    @Autowired
    private ITCrmCarSaMessageDao itCrmCarSaMessageDao;

    @Autowired
    private ITCrmCarRefDao carRefDao;


    private enum CARREFTYPE {
        ALL, LASTNUMBER, MATISSA
    }

    /**
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */

    private void createSql(Map map, String type) {


        Map<String, Object> has = new HashMap<String, Object>();
        String tmp = null;
        String tmps[] = null;
        //可能存在单个value字段1，2，3样式，需先分割开
        for (int i = 0; i < map.size(); i++) {
            if (map.get("value") == null) {
                continue;
            }
            tmp = map.get("value").toString();
            tmps = tmp.split(",");
            for (int j = 0; j < tmps.length; j++) {
                has.put(tmps[j], "1");
            }
        }
        Object obj[] = has.keySet().toArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < obj.length; i++) {
            sb.append(obj[i].toString());
        }

        //0全部、1 尾号、2 尾数、3 VIN、
        //生成过滤语句
        //String type = datas.get(0).get("type").toString();

        //------工单导入------

        // List params1 = new ArrayList();

        if (type.equals(String.valueOf(CARREFTYPE.LASTNUMBER.ordinal()))) {
            sb.append(" AND  wo.plate_num REGEXP '[" + sb.toString().replaceAll(",", "") + "]$' ");
        } else if (type.equals(String.valueOf(CARREFTYPE.MATISSA.ordinal()))) {
            sb.append(" AND wo.plate_num REGEXP '.*[" + sb.toString().replaceAll(",", "") + "][A-Za-z]*$' ");
        } else {//全部
            //分配全部车辆
            // return null;
        }


    }


    @Override
    public TCrmCarSaMessage saveOrder(String uid) throws Exception {

        String companyId = TokenUtil.getCompanyId(uid);
        List<Map<String, Object>> list = this.carRefDao.findUserByCompnayIdList(companyId);
        for (Map map : list) {
            List params1 = new ArrayList();
            String sql = "SELECT u.u_code ucode,wo.sa_id, COUNT(wo.create_time) count FROM t_crm_car_workorder wo LEFT JOIN t_crm_car_ref cr on wo.sa_id = cr.u_id LEFT JOIN t_bc_user u on u.id = wo.sa_id  WHERE 1=1";
            String type = String.valueOf(map.get("type"));
            String uId = String.valueOf(map.get("u_id"));
            //String uID = String.valueOf(map.get("u_id"));

            Map<String, Object> has = new HashMap<String, Object>();
            String tmp = null;
            String tmps[] = null;
            //可能存在单个value字段1，2，3样式，需先分割开
//            for (int i = 0; i < list.size(); i++) {
            if (map.get("value") == null) {
                continue;
            }
            tmp = map.get("value").toString();
            tmps = tmp.split(",");
            for (int j = 0; j < tmps.length; j++) {
                has.put(tmps[j], "1");
            }
//            }
            Object obj[] = has.keySet().toArray();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < obj.length; i++) {
                sb.append(obj[i].toString());
            }


            if (type.equals("1")) {

                sql += " AND  wo.plate_num REGEXP '[" + sb.toString().replaceAll(",", "") + "]$' ";

            } else if (type.equals("2")) {

                sql += " AND wo.plate_num REGEXP '.*[" + sb.toString().replaceAll(",", "") + "][A-Za-z]*$' ";
            } else {
                return null;
            }
            sql += " AND wo.company_id = ? AND cr.u_id = wo.sa_id AND cr.u_id = ? AND (wo.create_time between (wo.create_time-wo.create_time%(60*60*24*1000)) AND (wo.create_time-wo.create_time%(60*60*24*1000)+86400000)) group by cr.u_id, wo.create_time-wo.create_time%(60*60*24*1000)  ORDER BY wo.create_time desc limit 1";
            params1.add(TokenUtil.getCompanyId(uid));
            params1.add(uId);

            List<Map<String, Object>> listCount = this.itCrmCarSaMessageDao.list(sql, params1.toArray());


            for (Map map1 : listCount) {

                String name1 = String.valueOf(map1.get("ucode"));
               // System.out.println(name1 + "sa的姓名");
                String uid1 = String.valueOf(map1.get("saId"));
               // System.out.println(uid1);

                TCrmCarSaMessage sm = new TCrmCarSaMessage();
                sm.setCreateDate(new Date().getTime());
                sm.setCompanyId(TokenUtil.getCompanyId(uid));
                sm.setName(name1);
                sm.setSaid(uid1);
                if (map1.get("count") == null) {
                    sm.setCount("0");
                } else {

                    sm.setCount(String.valueOf(map1.get("count")));
                }
               // System.out.println(map1.get("count") + "统计的数量==========");
                sm.setStatus("0");
                sm.setType("新导入工单");
                sm.setCreateTime(new Date().getTime());
                sm.setCreateUser(uid);
                this.itCrmCarSaMessageDao.saveOrUpdate(sm);

                return sm;

            }
        }

        return null;

    }

    @Override
    public TCrmCarSaMessage saveCar(String uid) throws Exception {

        String companyId = TokenUtil.getCompanyId(uid);
        List<Map<String, Object>> list = this.carRefDao.findUserByCompnayIdList(companyId);

        List params1 = new ArrayList();

        for (Map map : list) {
            String sql = "SELECT u.u_code ucode,c.said, COUNT(c.create_time) FROM t_crm_car c LEFT JOIN t_crm_car_ref cr on c.said = cr.u_id LEFT JOIN t_bc_user u on u.id = c.said  WHERE 1=1";
            String type = String.valueOf(map.get("type"));
            String uId = String.valueOf(map.get("u_id"));


            Map<String, Object> has = new HashMap<String, Object>();
            String tmp = null;
            String tmps[] = null;
            //可能存在单个value字段1，2，3样式，需先分割开
//            for (int i = 0; i < list.size(); i++) {
            if (map.get("value") == null) {
                continue;
            }
            tmp = map.get("value").toString();
            tmps = tmp.split(",");
            for (int j = 0; j < tmps.length; j++) {
                has.put(tmps[j], "1");
            }
//            }
            Object obj[] = has.keySet().toArray();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < obj.length; i++) {
                sb.append(obj[i].toString());
            }


            if (type.equals("1")) {

                sql += " AND  c.plate_num REGEXP '[" + sb.toString().replaceAll(",", "") + "]$' ";

            } else if (type.equals("2")) {

                sql += " AND c.plate_num REGEXP '.*[" + sb.toString().replaceAll(",", "") + "][A-Za-z]*$' ";
            } else {
                return null;
            }
            sql += " AND c.company_id = ? AND cr.u_id = c.said AND cr.u_id = ? AND (c.create_time between (c.create_time-c.create_time%(60*60*24*1000)) AND (c.create_time-c.create_time%(60*60*24*1000)+86400000)) group by cr.u_id, c.create_time-c.create_time%(60*60*24*1000)  ORDER BY c.create_time desc limit 1";
            params1.add(TokenUtil.getCompanyId(uid));
            params1.add(uId);

            List<Map<String, Object>> listCount = this.itCrmCarSaMessageDao.list(sql, params1.toArray());

            for (Map map1 : listCount) {

                String name1 = String.valueOf(map1.get("ucode"));
                // System.out.println(name1 + "sa的姓名");
                String uid1 = String.valueOf(map1.get("said"));
                // System.out.println(uid1);

                TCrmCarSaMessage sm = new TCrmCarSaMessage();
                sm.setCreateDate(new Date().getTime());
                sm.setCompanyId(TokenUtil.getCompanyId(uid));
                sm.setName(name1);
                sm.setSaid(uid1);
                if (map1.get("count") == null) {
                    sm.setCount("0");
                } else {
                    sm.setCount(String.valueOf(map1.get("count")));
                }
                //System.out.println(map1.get("count") + "统计的数量==========");
                sm.setStatus("0");
                sm.setType("新匹配车辆");
                sm.setCreateTime(new Date().getTime());
                sm.setCreateUser(uid);
                this.itCrmCarSaMessageDao.saveOrUpdate(sm);

                return sm;

            }
        }

        return null;
    }


    @Override
    public Map page(String start, String limit, String uid) throws Exception {

        Map<String, String> map = TokenUtil.getRoleDate(uid);

        //----------------分页查询
        List params = new ArrayList<>();

        String sql = "select * from T_CRM_CAR_SAMESSAGE sm where 1=1";


        if (map.size() > 0) {
            for (String key : map.keySet()) {
                sql += " and (sm.said = ? or sm.company_id in (?))";
                params.add(uid);
                params.add(key);
            }
        } else {
            sql += " and sm.said = ? ";
            params.add(uid);
        }

        if (!StringUtils.isEmpty(uid)) {

            sql += " and sm.company_id = ? ";
            params.add(TokenUtil.getCompanyId(uid));

        }

        sql += " order by sm.create_time desc";

        return this.itCrmCarSaMessageDao.page(sql, params.toArray(), start, limit);
    }


}
